package com.wn.framework.utils

import android.app.Activity
import android.os.Handler
import android.os.Looper
import android.widget.Toast
import com.wn.framework.R
import kotlin.system.exitProcess

/**
 * @Author: wn
 * @Date: 2024/9/4 16:32
 * @Description: 连续两次退出程序
 */
object AppExit {

  private var preExit = false

  /**
   * 2秒延迟执行
   */
  private val handler = Handler(Looper.getMainLooper()) {
    preExit = false
    true
  }

  /**
   * 点击两次退出程序
   * @param activity Activity            -- 当前 Activity
   * @param tipCallback Function0<Unit>  -- 点击执行 lambda
   * @param exitCallback Function0<Unit> -- 退出执行 lambda
   */
  fun onBackPressed(
    activity: Activity,
    tipCallback: () -> Unit = {
      Toast.makeText(
        activity,
        activity.getString(R.string.base_app_exit_one_more_press),
        Toast.LENGTH_SHORT
      ).show()
    },
    exitCallback: () -> Unit = {},
  ) {
    if (!preExit) {
      preExit = true
      tipCallback()
      handler.sendEmptyMessageDelayed(0, 2000)
    } else {
      exitCallback()
      activity.finish()
      exitProcess(0)
    }
  }
}